const path = require('path')
const defaultSettings = require('./src/settings.js')
const CompressionPlugin = require('compression-webpack-plugin')


function resolve(dir) {
  return path.join(__dirname, dir)
}

const name = defaultSettings.title // 网址标题
const port = 5500 // 端口配置

module.exports = {
  publicPath: './',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    compress: false, // 禁用Gzip压缩
    port: port,
    open: true,
    client: {
      overlay: {
        warnings: false,
        errors: true
      }
    },
    proxy: {
      '/api': {
        // target: process.env.VUE_APP_BASE_API,
        target: 'http://172.31.69.119:8084',
        changeOrigin: true,
        pathRewrite: {
          '^/api': '/'
        }
      },
      '/auth': {
        target: 'http://134.103.65.136:7081',
        changeOrigin: true,
        pathRewrite: {
          '^/auth': '/'
        }
      },
      '/AIapi': {
        target: 'https://134.108.3.250:443',
        // target: 'http://134.103.65.136:7082',
        changeOrigin: true,
        pathRewrite: { '^/AIapi': '/' },
      },
      '/new': {
        // target: process.env.VUE_APP_BASE_API, // 真实的api地址
        target: 'http://134.103.65.136:7082', // 真实的api地址
        // target: 'http://172.31.69.76:7082/', // 真实的api地址
        changeOrigin: true,
        pathRewrite: {
          '^/new': '/'
        }
      },
      '/gateway': {
        // target: process.env.VUE_APP_BASE_API, // 真实的api地址
        target: 'http://134.103.65.136:8103', // 真实的api地址
        // target: 'http://172.31.69.76:7082/', // 真实的api地址
        changeOrigin: true,
        pathRewrite: {
          '^/gateway': '/'
        }
      },
      '/neibu': {
        // target: 'https://134.108.3.250:443',
        target: 'http://134.103.65.136:7082',
        changeOrigin: true,
        pathRewrite: { '^/neibu': '/' },
        // secure: false,
        // // 关键配置：禁用代理的 Gzip 压缩
        // onProxyReq: (proxyReq, req, res) => {
        //   // 告诉上游服务器不要返回压缩数据
        //   proxyReq.setHeader('Accept-Encoding', 'identity'); // 或 'gzip;q=0'
        // },
        // onProxyRes: (proxyRes, req, res) => {
        //   // 确保代理响应头正确设置
        //   proxyRes.headers['content-type'] = 'text/event-stream';
        //   proxyRes.headers['cache-control'] = 'no-cache';
        //   proxyRes.headers['connection'] = 'keep-alive';
        //   // 强制移除 Content-Encoding（如果上游服务器仍返回压缩数据）
        //   // delete proxyRes.headers['content-encoding'];
        // },
        onError: (err, req, res) => {
          console.error('Proxy error:', err);
          console.error('Proxy error:', req);
          console.error('Proxy error:', res);
          res.status(500).send('Proxy error');
        },
        // buffer: false // 禁用代理缓冲
      }
    }
  },
  configureWebpack: {
    name: name,
    resolve: {
      alias: {
        '@': resolve('src'),
        '@crud': resolve('src/components/Crud')
      }
    },
    plugins: [
      new CompressionPlugin({
        test: /\.(js|css|html)?$/i,
        // 修改 filename 选项
        filename: '[path][base].gz[query]',
        algorithm: 'gzip',
        minRatio: 0.8
      })
    ]
  },
  chainWebpack(config) {
    // 其他配置保持不变
    config.plugins.delete('preload')
    config.plugins.delete('prefetch')

    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()

    config
      .when(process.env.NODE_ENV === 'development',
        config => config.devtool('cheap-source-map')
      )

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial'
                },
                elementUI: {
                  name: 'chunk-elementUI',
                  priority: 20,
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'),
                  minChunks: 3,
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          config.optimization.runtimeChunk('single')
        }
      )
  },
  transpileDependencies: [
    'vue-echarts',
    'resize-detector'
  ]
}
